//
// Created by xkj on 2020/8/3.
//

#ifndef PROJ_ANDROID_NDK_CPP_UTILS_H
#define PROJ_ANDROID_NDK_CPP_UTILS_H

#include <jni.h>
#include <string>

using namespace std;

class NDK_CPP_Utils {
public:
        static void jstring2String(JNIEnv* env, jstring jstr, std::string &convertStr)
        {
            char* rtn = NULL;
            jclass clsstring = env->FindClass("java/lang/String");
            jstring strencode = env->NewStringUTF("utf-8");
            jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
            jbyteArray barr= (jbyteArray)(env)->CallObjectMethod( jstr, mid, strencode);
            jsize alen = (env)->GetArrayLength( barr);
            jbyte* ba = (env)->GetByteArrayElements( barr, JNI_FALSE);
            if (alen > 0)
            {
                rtn = (char*)malloc(alen + 1);
                memcpy(rtn, ba, alen);
                rtn[alen] = 0;
            }
            (env)->ReleaseByteArrayElements( barr, ba, 0);
            convertStr = rtn;
            free(rtn);
        }
};


#endif //PROJ_ANDROID_NDK_CPP_UTILS_H
